'use strict';

const Service = require('egg').Service;

class WorkWeChatService extends Service {
  async getAccessToken() {
    const { ctx, config } = this;
    const { WorkWeChat } = config;
    const { id, secret } = WorkWeChat;

    const result = await ctx.curl(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${id}&corpsecret=${secret}`, {
      dataType: 'json',
    });

    const assessToken = result.res.data.access_token;

    return assessToken;
  }

  async send(weather) {
    const { ctx, config } = this;
    const { WorkWeChat } = config;
    const { agentId, liqingshan } = WorkWeChat;
    const ACCESS_TOKEN = await this.getAccessToken();

    const postData = {
      touser: '@all',
      msgtype: 'text',
      agentid: agentId,
      text: {
        content: weather,
      },
    };

    const result = await ctx.curl(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${ACCESS_TOKEN}`, {
      method: 'POST',
      contentType: 'json',
      data: postData,
      dataType: 'json',
    });

    const data = result.res;

    return data;
  }
}

module.exports = WorkWeChatService;
